package com.zmx.patients.fragment.body_temperature;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.ChartTouchListener;
import com.github.mikephil.charting.listener.OnChartGestureListener;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.zmx.patients.R;
import com.zmx.patients.okhttp.OkHttp3ClientManager;
import com.zmx.patients.pojo.TimeQuantum;
import com.zmx.patients.utils.AllUtil;
import com.zmx.patients.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 程序猿：胖胖祥
 * 时 间：2020/10/18  12:37
 * 功 能：
 */
public class BodyChatFragment extends Fragment implements OnChartGestureListener, OnChartValueSelectedListener {

    private LineChart body_temperature;
    private LineData  bt_data;

    private List<TimeQuantum> bts;
    SimpleDateFormat sdFormatter = new SimpleDateFormat("HH:mm");
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_body_chat, container, false);

        body_temperature = view.findViewById(R.id.body_temperature);
        body_temperature.setOnChartGestureListener(this);
        body_temperature.setOnChartValueSelectedListener(this);
        body_temperature.setDrawGridBackground(false);
        // 无描述文本
        body_temperature.getDescription().setEnabled(false);
        // 使能点击
        body_temperature.setTouchEnabled(false);
        body_temperature.setScaleXEnabled(true);
        body_temperature.setScaleYEnabled(false);
        // 使能拖动和缩放
        body_temperature.setDragEnabled(true);
        body_temperature.setScaleEnabled(true);
        // 如果为false，则x，y两个方向可分别缩放
        body_temperature.setPinchZoom(true);
        getBts();
        return view;

    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what){

                case 1:

                    Log.e("发顺丰", "血压" + msg.obj.toString());
                    bts = new ArrayList<>();
                    try {

                        Log.e("发顺丰", "血压" + msg.obj.toString());
                        JSONObject object = new JSONObject(msg.obj.toString());
                        JSONObject data = object.getJSONObject("data");

                        JSONArray array = data.getJSONArray("list");
                        for (int i = 0; i < array.length(); i++) {

                            JSONObject o = array.getJSONObject(i);
                            TimeQuantum tq = new TimeQuantum();
                            tq.setTemp(o.getInt("temp"));
                            String s = sdFormatter.format(format.parse(o.getString("bttime")));
                            tq.setTime(s);
                            bts.add(tq);

                        }
                        bt_data = getBt_data(bts);
                        body_temperature.setData(bt_data);
                        body_temperature.animateX(2000);//动画时间

                    } catch (JSONException e) {

                        e.printStackTrace();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }


                    break;

            }
        }
    };

    //获取温度
    private LineData getBt_data(List<TimeQuantum> tqs) {

        //设置x轴位置
        XAxis xAxis = body_temperature.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        //设置X轴上每个竖线是否显示
        xAxis.setDrawGridLines(true);
        //设置是否绘制X轴上的对应值(标签)
        xAxis.setDrawLabels(true);
        //设置x轴间距
        xAxis.setGranularity(1f);
//        xAxis.setLabelCount(tqs.size(),true);
        xAxis.setLabelCount(10);//一个界面显示10个Lable。那么这里要设置11个
        xAxis.setLabelRotationAngle(-30);

        // 横坐标文字
        xAxis.setValueFormatter((value, axis) -> {


            if (tqs.size() < 3) {
                return "";
            }


            //报null
            if (value < tqs.size()) {

                String str = tqs.get((int) value).getTime();

                return str;

            } else {

                return null;

            }


        });

        //去除右边的y轴
        YAxis yAxisRight = body_temperature.getAxisRight();
        yAxisRight.setEnabled(false);

        ArrayList<Entry> yVals1 = new ArrayList<Entry>();
        for (int i = 0; i < tqs.size(); i++) {
            // 要显示的数据
            yVals1.add(new Entry(i, Float.parseFloat(tqs.get(i).getTemp() + "")));

        }

        //一条曲线对应一个LineDataSet
        LineDataSet set1 = new LineDataSet(yVals1, "体温");
        set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);//设置曲线为圆滑的线
        set1.setCubicIntensity(0.2f);
        set1.setValueTextSize(8f);
        set1.setDrawCircles(true);  //设置有圆点
        set1.setDrawValues(false);
        set1.setLineWidth(0.8f);    //设置线的宽度
        set1.setCircleSize(1f);   //设置小圆的大小

        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        dataSets.add(set1); // add the datasets
        LineData data = new LineData(dataSets);

        return data;
    }


    public void getBts(){

        List<String> l = new ArrayList<>();
        l.add("");
        l.add(MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.uid, ""));
        l.add("");
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(l)));
        params.put("token", MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getBts");
        params.put("data[patient_id]", MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.uid, ""));
        params.put("data[starttime]", "");
        params.put("data[endtime]", "");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/watch", params, handler, 1, 404);

    }




    //签名
    public String sing(List<String> list) {

        StringBuilder requestparams = new StringBuilder();
        requestparams.append(MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.uid, "") +
                MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.role, "") +
                System.currentTimeMillis() / 1000 + MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.password, ""));

        if (list != null) {
            for (String s : list) {
                requestparams.append(s);
            }
        }
        return requestparams.toString();

    }

    @Override
    public void onChartGestureStart(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {

    }

    @Override
    public void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {

    }

    @Override
    public void onChartLongPressed(MotionEvent me) {

    }

    @Override
    public void onChartDoubleTapped(MotionEvent me) {

    }

    @Override
    public void onChartSingleTapped(MotionEvent me) {

    }

    @Override
    public void onChartFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY) {

    }

    @Override
    public void onChartScale(MotionEvent me, float scaleX, float scaleY) {

    }

    @Override
    public void onChartTranslate(MotionEvent me, float dX, float dY) {

    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {

    }

    @Override
    public void onNothingSelected() {

    }
}

